package com.itcoon.transform.base.register.unannotated;

import com.itcoon.transform.base.definition.ModelDefinition;
import com.itcoon.transform.base.definition.ModelPropertyDefinition;
import com.itcoon.transform.base.utils.TransformServiceUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class UnAnnotatedIInterAssembleModelRegister implements UnAnnotedAssembleModelRegister{

    @Override
    public boolean support(Class<?> targetClass) {
        return targetClass.isInterface();
    }

    @Override
    public void register(ModelDefinition modelDefinition) throws IntrospectionException{
        Class<?> targetClass = modelDefinition.getTargetClass();
        BeanInfo targetBeanInfo = Introspector.getBeanInfo(targetClass);
        PropertyDescriptor[] targetPropertyDescriptors = targetBeanInfo.getPropertyDescriptors();
        for (PropertyDescriptor targetPropertyDescriptor : targetPropertyDescriptors) {
            Method targetGetter = targetPropertyDescriptor.getReadMethod();
            ModelPropertyDefinition mpd = new ModelPropertyDefinition(modelDefinition);
            mpd.setTargetGetter(targetGetter);
            mpd.setTargetAttribute(targetPropertyDescriptor.getName());
            mpd.setTargetPropertyType(targetPropertyDescriptor.getPropertyType());
            mpd.setAnnotated(false);
            String originAttribute  = mpd.getTargetAttribute();
            originAttribute = targetGetter.isDefault() ? null : originAttribute;
            mpd.setOriginAttribute(originAttribute);
            if(originAttribute != null){
                // 根据originAttribute 是否包含”." 级联获取元对象的getter
                Method originGetter = TransformServiceUtils.findGetterFromValue(modelDefinition.getOriginClass(), originAttribute);
                if(originGetter == null){
                    continue;
                }
                mpd.setOriginGetter(originGetter);
            }
            modelDefinition.getPropertyDefinitions().add(mpd);
        }
    }
}
